package com.leyou.item.mapper;

import com.leyou.common.mapper.BaseMapper;
import com.leyou.item.domain.Permission;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Date: 2019/11/28
 * Author: L
 * Description: 权限mapper
 */
@Repository

public interface PermissionMapper extends BaseMapper<Permission> {

    /**
     * 根据角色id查询权限,但是前端参数显示的是pid
     * @param rid 角色id
     * @return
     */
    @Select("SELECT sp.* FROM sys_role sr,sys_role_permission srp, sys_permission sp " +
            "WHERE sr.id = srp.rid AND srp.pid = sp.id AND sr.id=#{pid}")
    List<Permission> queryByRoleId(@Param("pid") Integer rid);

    /**
     * 向角色权限中间表中添加数据
     * @param roleId    角色id
     * @param permissionId 权限id
     */
    @Insert("INSERT INTO sys_role_permission VALUES(#{rid}, #{pid})")
    void insertRoleAndPermission(@Param("rid") Integer roleId, @Param("pid") Integer permissionId);


    @Select("select * from sys_permission")
    List<Permission> findAllPermissionPath();

    @Select("SELECT sr.role_name FROM sys_role_permission srp ,sys_role sr WHERE srp.rid = sr.id AND srp.pid = #{pid}")
    List<String> findAllRoleByPermission(Integer pid);


    @Select("SELECT * FROM sys_permission WHERE path = #{path}")
    Permission findPermissionByPath(String path);


    /**
     * 根据用户id来查找权限的信息
     * @param uid  用户id
     * @return
     */
    @Select("SELECT DISTINCT p.`id`,p.`name`,p.path,p.`action`,p.`parent_id` parentId FROM sys_user_role ur," +
            "sys_role_permission rp," +
            "sys_permission p " +
            "WHERE ur.`UID`=#{uid} AND rp.`RID`=ur.`RID` AND p.`ID`=rp.`PID`")
    List<Permission> findPermissionByUserId(Integer uid);

    /**
     * 根据uid查询父权限
     * @param uid
     * @return
     */
    @Select("SELECT id,name,path,action,parent_id parentId FROM sys_permission WHERE id IN (SELECT DISTINCT p.`parent_id` FROM sys_user_role ur," +
            "sys_role_permission rp," +
            "sys_permission p WHERE ur.`UID`=#{uid} AND rp.`RID`=ur.`RID` AND p.`ID`=rp.`PID`)"
            )
    List<Permission> findPermissionFatherByUserId(Integer uid);
}
